package org.nf.ssm.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.nf.ssm.common.ResultVO;
import org.nf.ssm.common.exception.ErrorsEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zhu
 * @date 2024-10-14
 */
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器····");
        if("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("loginAdmin") != null) {
            return true;
        }
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            ResultVO vo = new ResultVO();
            vo.setCode(ErrorsEnum.AUTH_EXCEPTION.errorCode());
            vo.setMessage(ErrorsEnum.AUTH_EXCEPTION.errorMessage());
            response.setContentType("application/json;charset=utf-8");
            String json = new ObjectMapper().writeValueAsString(vo);
            response.getWriter().write(json);
        } else {
            response.sendRedirect("/layui/login.html");
        }
        return false;
    }
}
